package com.aiju.cash.ui.account;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Account;
import com.aiju.cash.R;
import com.aiju.cash.core.api.AccountApi;
import com.aiju.cash.core.event.AccountEvent;
import com.aiju.cash.ui.account.adapter.AccountInfoAdapter;
import com.aiju.cash.ui.account.entity.Budget;
import com.aiju.cash.ui.account.entity.ItemList;
import com.aiju.cash.util.GsonHelper;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.utils.DateUtil;
import com.aiju.utils.Util;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.fangxu.allangleexpandablebutton.AllAngleExpandableButton;
import com.fangxu.allangleexpandablebutton.ButtonData;
import com.fangxu.allangleexpandablebutton.ButtonEventListener;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import java.util.ArrayList;
import java.util.List;


/**
 * @author: 佐为
 * @date: 2017-03-29 09:55
 * @version: V1.0
 * @Description: 账目详情
 */
public class AccountInfoActivity extends BaseTitleActivity implements SwipeRefreshHelper.OnSwipeRefreshListener, OnLoadMoreListener {

    private Account mAccount;

    private AccountApi mAccountApi;

    private TextView monthTextView, budgetTextView;
    private TextView inTextView, outTextView;

    private AccountInfoAdapter infoAdapter;
    private RecyclerView recyclerView;


    private StickyRecyclerHeadersDecoration headersDecor;
    private SwipeRefreshLayout mSryt;
    private SwipeRefreshHelper mSwipeRefreshHelper;
    private RecyclerAdapterWithHF mAdapter;

    private int pageSize = 10;
    private int currentNum = 1;

    private boolean isLoad;
    private boolean isRefresh;
    private View emptyView;

    private List<ItemList.DateItem> categoryList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_item);

        mAccount = (Account) getIntent().getSerializableExtra("account");
        setCenterTitle(mAccount.getName());

        mAccountApi = new AccountApi(mDialogHelper);
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.mipmap.ic_account_calendar);
        mAiJuTitleBarView.setCustomizedRightView(imageView);
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountInfoActivity.this, AccountCalendarActivity.class);
                intent.putExtra("accountId", mAccount.getId());
                startActivity(intent);
            }
        });

        emptyView = findViewById(R.id.iv_empty);
        budgetTextView = (TextView) findViewById(R.id.tv_budget_type);
        monthTextView = (TextView) findViewById(R.id.tv_budget_money);
        monthTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountInfoActivity.this, AccountBudgetActivity.class);
                intent.putExtra("accountId", mAccount.getId());
                if (!TextUtils.isEmpty(budget.getBudgetType())) {
                    intent.putExtra("budgetType", Integer.valueOf(budget.getBudgetType()));
                } else {
                    intent.putExtra("budgetType", 3);
                }
                intent.putExtra("budgetMoney", budget.getBudgetMoney());
                startActivity(intent);
            }
        });

        inTextView = (TextView) findViewById(R.id.tv_account_in);
        outTextView = (TextView) findViewById(R.id.tv_account_out);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        mSryt = (SwipeRefreshLayout) this.findViewById(R.id.sryt_swipe_listview);
        mSryt.setColorSchemeColors(getResources().getColor(R.color.app_title_color));
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSryt);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(this);
        mSwipeRefreshHelper.setOnLoadMoreListener(this);

        TextView monthIn = (TextView) findViewById(R.id.tv_month_in);
        TextView monthOut = (TextView) findViewById(R.id.tv_month_out);
        monthIn.setText(DateUtil.getCurrentDate(DateUtil.dateFormatM) + "收入");
        monthOut.setText(DateUtil.getCurrentDate(DateUtil.dateFormatM) + "支出");

        AllAngleExpandableButton button = (AllAngleExpandableButton) findViewById(R.id.button_expandable);
        final List<ButtonData> buttonDatas = new ArrayList<>();
        int[] color = {R.color.color_add, R.color.color_in, R.color.color_out};
        for (int i = 0; i < color.length; i++) {
            ButtonData buttonData;
            if (i == 0) {
                buttonData = ButtonData.buildIconButton(this, R.mipmap.ic_account_add, 0);
            } else if (i == 1) {
                buttonData = ButtonData.buildIconButton(this, R.mipmap.ic_account_add_in, 0);
            } else {
                buttonData = ButtonData.buildIconButton(this, R.mipmap.ic_account_add_out, 0);
            }
            buttonData.setBackgroundColorId(this, color[i]);
            buttonDatas.add(buttonData);
        }
        button.setButtonDatas(buttonDatas);
        button.setButtonEventListener(new ButtonEventListener() {
            @Override
            public void onButtonClicked(int index) {
                if (index == 1) {
                    Intent intent = new Intent(AccountInfoActivity.this, AccountCreatActivity.class);
                    intent.putExtra("accountId", mAccount.getId());
                    intent.putExtra("type", "1");
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(AccountInfoActivity.this, AccountCreatActivity.class);
                    intent.putExtra("accountId", mAccount.getId());
                    intent.putExtra("type", "2");
                    startActivity(intent);
                }
            }

            @Override
            public void onExpand() {
            }

            @Override
            public void onCollapse() {
            }
        });

        requesetAccountInfo();
        requsetBudget();
        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(AccountEvent event) {
                if (event.type == 0) {
                    requsetBudget();
                }
                if (event.type == 1) {
                    currentNum = 1;
                    categoryList.clear();
                    requesetAccountInfo();
                    requsetBudget();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAccountApi.setDialogHelper(mDialogHelper);
    }

    private Budget budget;

    /**
     * 请求预算
     */
    private void requsetBudget() {
        mAccountApi.get(mAccount.getId(), new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {

                budget = GsonHelper.convertEntity(data, Budget.class);
                budgetTextView.setText(budget.getBudgetTypeString());
                if (TextUtils.isEmpty(budget.getBudgetMoney())) {
                    monthTextView.setTextColor(Color.parseColor("#99ffffff"));
                    monthTextView.setText("请设置预算");
                } else {
                    monthTextView.setTextColor(Color.WHITE);
                    monthTextView.setText(budget.getSurplusMoney());
                }
            }
        });
    }

    /**
     * 列表
     */
    private void requesetAccountInfo() {
        mAccountApi.itemList(mAccount.getId(), String.valueOf(currentNum), String.valueOf(pageSize), new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                ItemList item = GsonHelper.convertEntity(data, ItemList.class);
                if (Util.isEmpty(categoryList)) {
                    categoryList.addAll(item.getList());
                } else {
                    ItemList.DateItem lastDateItem = categoryList.get(categoryList.size() - 1); //原数据最后一个
                    List<ItemList.DateItem> newlist = item.getList();
                    for (ItemList.DateItem newDateItem : newlist) {
                        if (lastDateItem.getDate().equals(newDateItem.getDate())) {
                            lastDateItem.getList().addAll(newDateItem.getList());
                        } else {
                            categoryList.add(newDateItem);
                        }
                    }
                }

                if (recyclerView.getAdapter() == null) {
                    infoAdapter = new AccountInfoAdapter(categoryList);
                    mAdapter = new RecyclerAdapterWithHF(infoAdapter);
                    infoAdapter.setOnItemClickListener(new AccountInfoAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(ItemList.Item item) {
                            Intent intent = new Intent(AccountInfoActivity.this, AccountItemInfoActivity.class);
                            intent.putExtra("item", item);
                            startActivity(intent);
                        }
                    });
                    recyclerView.setAdapter(mAdapter);
                    headersDecor = new StickyRecyclerHeadersDecoration(infoAdapter);
                    recyclerView.addItemDecoration(headersDecor);
                } else {
                    infoAdapter.dataChange(categoryList);
                    headersDecor.invalidateHeaders();
                }

                for (ItemList.Sum sum : item.getSum()) {
                    if (sum.getType() == 1) {
                        inTextView.setText(sum.getMoney());
                    }
                    if (sum.getType() == 2) {
                        outTextView.setText(sum.getMoney());
                    }
                }

                completeView(item.getAllItem());
                if (infoAdapter.isEmpty()) {
                    findViewById(R.id.iv_empty).setVisibility(View.VISIBLE);
                    mAiJuTitleBarView.getRightViewContainer().setVisibility(View.INVISIBLE);
                    recyclerView.setVisibility(View.GONE);
                } else {
                    findViewById(R.id.iv_empty).setVisibility(View.GONE);
                    mAiJuTitleBarView.getRightViewContainer().setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void loadMore() {
        isLoad = true;
        currentNum += 1;
        requesetAccountInfo();
    }

    @Override
    public void onfresh() {
        isRefresh = true;
        currentNum = 1;
        categoryList.clear();
        requesetAccountInfo();
    }

    /**
     * 加载完成视图动作
     *
     * @param blotterLists
     */
    private void completeView(List<ItemList.Item> blotterLists) {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }

        if (blotterLists.size() < pageSize) {
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        } else {
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (infoAdapter != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = infoAdapter.isEmpty();
            if (emptyViewVisible) {
                emptyView.setVisibility(View.VISIBLE);
            } else {
                emptyView.setVisibility(View.GONE);
            }
        }
    }
}
